<template>
  <view>
      <view class="custom" @click="gotoTrendPublish">
        <view>发圈</view>
      </view>
      <view class="tip" v-if="trendList.length<=0">暂时没有动态哦~</view>
    <view class="trend-box" v-for="(item, i) in modifiedTrendList" :key="i" v-else>
      <uni-card :title="item.nickName" :sub-title="item.createTime" :thumbnail="item.avatarUrl"
        :border="false" shadow="0px 1px 2px 0.1px #eee" :extra="item.position ? item.position : null">
        <view class="image-box" v-if="item.imageList.length > 1">
          <view class="image-item" v-for="(item2, i2) in item.imageList" :key="i2">
            <image class="image-img" @click="preview(i2, item.imageList)" mode="aspectFill" :src="item2"></image>
          </view>
        </view>

        <image class="image-box-img" style="width: 100%;" mode="widthFix" :src="item.imageList"
          v-if="item.imageList.length === 1"></image>
        <text class="uni-body uni-mt-5">{{item.content}}</text>
        <view slot="actions" class="card-actions">
          <view class="card-actions-item" @click="shareTrend">
            <uni-icons class="card-actions-item-icon" type="redo" size="18" color="#999"></uni-icons>
            <text class="card-actions-item-text">分享</text>
          </view>
          <view class="card-actions-item" @click="likeTrend(item)">
            <uni-icons type="heart" size="18" color="#999" v-if="!item.isLiked"></uni-icons>
            <uni-icons type="heart-filled" size="18" color="#fba007" v-else></uni-icons>
            <text class="card-actions-item-number">{{ formatLikes(item.likeNum) }}</text>
          </view>
          <view class="card-actions-item" @click="commentTrend">
            <uni-icons type="chatbubble" size="18" color="#999"></uni-icons>
            <text class="card-actions-item-text">评论</text>
          </view>
        </view>
      </uni-card>
    </view>
    <view>
      <!-- 分享底部弹出层 -->
      <uni-popup ref="popup" type="bottom" is-mask-click="true" safeArea backgroundColor="white">
        <uni-popup-share></uni-popup-share>
      </uni-popup>
    </view>
    <view class="topping-icon" v-show="showTopBtn" @click="scrollToTop">
      <image src="../../static/stop_imgs/topping.png"></image>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    computed: {
      ...mapState('m_trend', ['trendList']),
      ...mapState('m_user', ['token', 'userinfo','userLikeTrendList']),
    },
    components: {},
    data() {
      return {
        modifiedTrendList: [],
        // 点赞按钮状态
        islike: false,
        // 节流阀：是否正在请求数据
        isloading: false,
        // 置顶按钮显示隐藏标志
        showTopBtn: false,
      };
    },
    onShow() {
      this.getTrendList()
    },
    // 监听页面滚动事件
    onPageScroll(e) {
      if (e.scrollTop > 0) {
        this.showTopBtn = true
      } else {
        this.showTopBtn = false
      }
    },
    methods: {
      ...mapMutations('m_user', ['updateUserLikeTrendList', 'deleteUserLikeTrendListItem', 'addUserTrendListLikeNum',
        'deleteUserTrendListLikeNum','updateUserTrendList'
      ]),
      ...mapMutations('m_trend', ['updateTrendList', 'addTrendListLikeNum', 'deleteTrendListLikeNum']),
      // 获取动态列表
      async getTrendList(cb) {
        this.isloading = true
        const {
          data: res
        } = await uni.$http.post('/api/get/trendWorks')
        this.isloading = false
        // 只要数据请求完毕，就立即按需调用 cb 回调函数
        cb && cb()
        console.log('后端返回的动态获取结果', res)
        if(res.meta.status !== 200) return $showMsg('动态获取失败')
        console.log('动态获取信息',res.message)
        this.updateTrendList(res.message)

        // 将 createTime 参数转换为时间差字符串
        const modifiedTrendList = this.trendList.map(trend => {
          return {
            ...trend,
            createTime: this.getRelativeTime(trend.createTime)
          };
        });

        modifiedTrendList.forEach(trend => {
          trend.isLiked = this.userLikeTrendList.some(likeTrend => likeTrend.id === trend.id);
        });

        console.log(modifiedTrendList);


        this.modifiedTrendList = modifiedTrendList
      },

      // 计算并格式化动态的点赞值
      formatLikes(likeNum) {
        if (likeNum >= 10000) {
          return (likeNum / 10000).toFixed(1) + 'w';
        } else if (likeNum >= 1000) {
          return (likeNum / 1000).toFixed(1) + 'k';
        } else {
          return likeNum.toString();
        }
      },

      //计算动态创建时间和当下时间的距离
      getRelativeTime(time) {
        const target = new Date(time);
        const now = new Date();

        const diff = now - target;

        const seconds = Math.floor(diff / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);
        const months = Math.floor(days / 30);
        const years = Math.floor(months / 12);

        if (years > 0) {
          return years + '年前';
        } else if (months > 0) {
          return months + '月前';
        } else if (days > 0) {
          return days + '天前';
        } else if (hours > 0) {
          return hours + '小时前';
        } else if (minutes > 0) {
          return minutes + '分钟前';
        } else if (seconds > 10) {
          return seconds + '秒前';
        } else {
          return '刚刚';
        }
      },

      // 点击"发圈"按钮跳转发表页面事件
      gotoTrendPublish() {
        if(!this.token) return uni.$showMsg('请先登录')
        uni.navigateTo({
          url: '../../subpkg/trend-publish/trend-publish'
        })
      },
      onClick(e) {
        console.log(e)
      },
      // 点击分享按钮事件
      shareTrend() {
        this.$refs.popup.open()
        return uni.$showMsg('待开发中')
      },
      // 点赞按钮事件
      likeTrend(item) {
        const trend = item
        const trendId = item.id
        // 使用Array.find方法查找匹配的对象
        const foundObject = this.trendList.find(item => item.id === trendId);
        foundObject.likeNum++
        // 获取createTime值
        const createTime = foundObject ? foundObject.createTime : null;
        var trendLikeNum = item.likeNum
        const userID = this.userinfo.userID
        
        if (trend.isLiked === false) {
          trend.isLiked = true
          trend.likeNum++
          trendLikeNum++
          
          const index = this.userLikeTrendList.findIndex(obj => obj.id === trendId);
          if (index === -1) {
            this.updateUserLikeTrendListToServer(foundObject)
            this.updateTrendListLikeNumToServer(trendId,trendLikeNum)
            if (trend.userId === userID) {
              this.updateUserTrendListLikeNumToServer(createTime,trendLikeNum)
            }
          } else {
            return uni.$showMsg('已点赞啦！')
          }
        } else {
          trend.isLiked = false
          trend.likeNum--
          trendLikeNum--
          
          const index = this.userLikeTrendList.findIndex(obj => obj.id === trendId);
          if (index !== -1) {
            this.deleteUserLikeTrendListToServer(createTime)
            // this.deleteTrendListLikeNum(trendId)
            this.updateTrendListLikeNumToServer(trendId,trendLikeNum)
            if (trend.userId === userID) {
              console.log('请求服务器更新用户作品喜欢人数')
              // this.deleteUserTrendListLikeNum(createTime)
              this.updateUserTrendListLikeNumToServer(createTime,trendLikeNum)
            }
          } else {
            return uni.$showMsg('取消点赞失败！')
          }
        }
      },
      // 请求服务器更新作品喜欢人数
      async updateTrendListLikeNumToServer(trendId,trendLikeNum) {
        // 准备参数
        const query = {
          trendId,
          trendLikeNum,
        }
        const {
          data: res
        } = await uni.$http.post('/api/update/trendListLikeNum', query)
        console.log('后端返回的发表结果', res)
        if(res.meta.status !== 200) return $showMsg('发表失败')
      },
      // 请求服务器更新用户作品喜欢人数
      async updateUserTrendListLikeNumToServer(createTime,trendLikeNum) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          createTime,
          trendLikeNum,
        };
        const {
          data: res
        } = await uni.$http.post('/api/update/userTrendListLikeNum', query)
        if (res.meta.status !== 200) return uni.$showMsg('更新作品喜欢人数失败')
        this.updateUserTrendList(res.message)
      },


      // 请求服务器更新用户喜欢的作品列表
      async updateUserLikeTrendListToServer(trend) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          trend,
        };
        const {
          data: res
        } = await uni.$http.post('/api/update/likeWorks', query)
        if (res.meta.status !== 200) return uni.$showMsg('更新喜欢作品列表失败')
        this.updateUserLikeTrendList(res.message)
      },
      // 请求服务器删除用户喜欢的作品列表
      async deleteUserLikeTrendListToServer(createTime) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          createTime,
        };
        const {
          data: res
        } = await uni.$http.post('/api/delete/likeWorks', query)
        if (res.meta.status !== 200) return uni.$showMsg('删除喜欢作品列表失败')
        this.updateUserLikeTrendList(res.message)
      },


      // 点击评论按钮事件
      commentTrend() {
        return uni.$showMsg('待开发中')
      },
      // 实现轮播图的预览效果
      preview(index, urls) {
        // 调用 uni.previewImage() 方法预览图片
        uni.previewImage({
          // 预览时，默认显示图片的索引
          current: index,
          // 所有图片 url 地址的数组
          urls,
        })
      },
      // 点击置顶按钮回到顶部事件
      scrollToTop() {
        if(this.showTopBtn === true) {
          uni.pageScrollTo({
            scrollTop: 0,
            duration: 0
          })
        }
      },
      // 监听上拉触底的事件
      // onReachBottom() {
      //   if (this.isloading) return
      //   // 判断是否还有下一页数据
      //   // if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕！')
      //   // 让页码值自增 +1
      //   // this.queryObj.pagenum++
      //   this.getTrendList()
      // },
      // 下拉刷新的事件
      onPullDownRefresh() {
        // 重置关键数据
        // this.queryObj.pagenum = 1
        // this.total = 0
        this.isloading = false
        // this.goodsList = []
        // 重新发起请求
        this.getTrendList(() => uni.stopPullDownRefresh())
      }
    }
  }
</script>

<style lang="scss">
  page {
    padding-bottom: 1rpx;
  }
  .custom {
    height: 80rpx;
    margin: 30rpx;
    border-radius: 15rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 11pt;
    font-weight: bold;
    background-color: #fba007;
    color: white;
    box-shadow: 0px 1px 2px 0.1px #ddd;
  }
  .tip {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #ccc;
      font-size: 34rpx;
  }
  .trend-box {

    .image-box {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10rpx;
      // border: 1px solid red;

      .image-item {
        width: 200rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding-top: 10rpx;
        margin-left: 1rpx;

        .image-img {
          width: 195rpx;
          height: 195rpx;
          background: whitesmoke;
          border-radius: 10rpx;
        }
      }
    }

    .image-box-img {
      background: whitesmoke;
      border-radius: 10rpx;
    }

    .card-actions {
      height: 42px;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      // border: 1px solid red;
      // border-top: 1px #DCDCDC solid;
      border-top: 1px #eee solid;

      // padding: 10px 0;
      .card-actions-item {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;

        .card-actions-item-icon {
          // top: 2px;
          text-align: center;
          // border: 1px solid red;
          // padding-top: 5px;
        }

        .card-actions-item-text {
          font-size: 12px;
          color: #6a6a6a;
          text-align: center;
          font-weight: 400;
          margin-left: 5px;
        }

        .card-actions-item-number {
          font-size: 12px;
          color: #6a6a6a;
          text-align: center;
          font-weight: 400;
          margin-left: 5px;
          margin-top: 3rpx;
        }
      }
    }
  }
  .topping-icon {
    width: 38px;
    height: 38px;
    position: sticky;
    bottom: 8px;
    z-index: 999;
    border: 1px solid #ccc;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    float: right;
    margin-right: 8px;
  
    image {
      width: 22px;
      height: 22px;
    }
  }
</style>